package com.lei.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;

public class UrlRewriteFilter extends OncePerRequestFilter {

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
																			throws ServletException, IOException {
		String uri = request.getRequestURI();
		int end = uri.lastIndexOf("-eng.html");
		
		if (end < 0) {
			end = uri.lastIndexOf("-fra.html");
			if (end >= 0) {
				request.setAttribute("lang", "fr");
			}
		} else {
			request.setAttribute("lang", "en");
		}
		
		if (end >= 0) {
			int start = uri.lastIndexOf('/', end);
			String path = uri.substring(start, end);
			RequestDispatcher rs = request.getRequestDispatcher(path + ".html");
			rs.forward(request, response);
		} else {
			chain.doFilter(request, response);
		}
	}

}
